package com.zyylr.classroomreservationsystem.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baoyz.widget.PullRefreshLayout;
import com.diegodobelo.expandingview.ExpandingItem;
import com.diegodobelo.expandingview.ExpandingList;
import com.zyylr.classroomreservationsystem.R;
import com.zyylr.classroomreservationsystem.bean.Building;
import com.zyylr.classroomreservationsystem.bean.Classroom;
import com.zyylr.classroomreservationsystem.bean.LoginUser;
import com.zyylr.classroomreservationsystem.bean.Msg;
import com.zyylr.classroomreservationsystem.bean.Reservation;

import com.zyylr.classroomreservationsystem.web.IReservation;
import com.zyylr.classroomreservationsystem.web.RetrofitFactory;

import java.util.List;

import com.zyylr.classroomreservationsystem.consts.GlobalConsts;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;


public class MyReservationActivity extends MyBaseCompatActivity {
    private static final String TAG = "我的预约";
    private ExpandingList reservationExpandingList;
    private PullRefreshLayout pullRefreshLayout;
    /**
     * 从服务器中得到的数据
     */
    private List<Reservation> reservationList;
    /**
     * 按照月份将reservationList划分为不同的组，如
     * {
     * 2019年5月=[Reservation1,Reservation2]
     * }
     */
    private Map<Date, List<Reservation>> reservationsMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_reservation);

        reservationExpandingList = findViewById(R.id.my_reservation_list);
        pullRefreshLayout = findViewById(R.id.swipeRefreshLayout_main);
        pullRefreshLayout.setRefreshStyle(PullRefreshLayout.STYLE_WATER_DROP);
        pullRefreshLayout.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pullRefreshLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        reservationExpandingList.removeAllViews();
                        sendHttpRequest();
                    }
                }, 0);
            }
        });
        pullRefreshLayout.setRefreshing(true);
        sendHttpRequest();
    }


    /**
     * 使用框架向服务器发送请求，得到响应数据存放在reservationList中
     */
    private void sendHttpRequest() {
        Retrofit retrofit = RetrofitFactory.getRetrofit();
        IReservation request = retrofit.create(IReservation.class);
        Call<Msg<List<Reservation>>> msgCall = request.getReservationCallByUser(LoginUser.getInstance());
        msgCall.enqueue(new Callback<Msg<List<Reservation>>>() {
            @Override
            public void onResponse(Call<Msg<List<Reservation>>> call, Response<Msg<List<Reservation>>> response) {
                Msg msg = response.body();
                Log.d(TAG, "msg= " + msg);
                try {
                    assert msg != null;
                    if (msg.getCode() == 200) {
                        Toast.makeText(getApplicationContext(), msg.getMsg(), Toast.LENGTH_SHORT).show();
                        pullRefreshLayout.setRefreshing(false);
                        return;
                    }
                    reservationList = (List<Reservation>) msg.getExtend().get("reservations");
                    Log.d(TAG, "reservationList= " + reservationList);
                    cleanData();
                    createItems();
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "数据解析错误！", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, e.getMessage());
                } finally {
                    pullRefreshLayout.setRefreshing(false);
                }
            }

            @Override
            public void onFailure(Call<Msg<List<Reservation>>> call, Throwable t) {
                Toast.makeText(getApplicationContext(), "服务请求错误！", Toast.LENGTH_SHORT).show();
                pullRefreshLayout.setRefreshing(false);
            }
        });
    }


    /**
     * 使用服务器返回的数据创建expanding listview item
     */
    private void createItems() {
        if (reservationList == null) {
            Log.d(TAG, "createItems: reservationList为空！");
            return;
        }
        for (Map.Entry<Date, List<Reservation>> entry : reservationsMap.entrySet()) {
            Date yearMonth = entry.getKey();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(yearMonth);
            //TODO:根据不同的月份设置不同的颜色和图标
            int colorRes = R.color.green, iconRes = R.drawable.may;

            switch (calendar.get(Calendar.MONTH)) {
                case Calendar.JANUARY:
                    iconRes = R.drawable.january;
                    break;
                case Calendar.FEBRUARY:
                    iconRes = R.drawable.february;
                    break;
                case Calendar.MARCH:
                    iconRes = R.drawable.march;
                    break;
                case Calendar.APRIL:
                    iconRes = R.drawable.april;
                    break;
                case Calendar.MAY:
                    iconRes = R.drawable.may;
                    break;
                case Calendar.JUNE:
                    iconRes = R.drawable.june;
                    break;
                case Calendar.JULY:
                    iconRes = R.drawable.july;
                    break;
                case Calendar.AUGUST:
                    iconRes = R.drawable.august;
                    break;
                case Calendar.SEPTEMBER:
                    iconRes = R.drawable.september;
                    break;
                case Calendar.NOVEMBER:
                    iconRes = R.drawable.november;
                    break;
                case Calendar.DECEMBER:
                    iconRes = R.drawable.december;
                    break;
            }

            //设置预约日期
            ExpandingItem item = reservationExpandingList.createNewItem(R.layout.layout_my_reservation_date);
            item.setIndicatorColor(colorRes);
            item.setIndicatorIconRes(iconRes);
            TextView reservationDate = item.findViewById(R.id.tv_my_reservation_date);
            reservationDate.setText(new SimpleDateFormat("yyyy年M月", Locale.CHINA).format(yearMonth));

            //设置具体预约记录
            List<Reservation> reservations = entry.getValue();
            //有多少记录就创建多少个子view
            item.createSubItems(reservations.size());
            for (int i = 0; i < item.getSubItemsCount(); i++) {
                View subView = item.getSubItemView(i);
                Reservation reservation = reservations.get(i);
                Integer status = reservation.getStatus();
                ImageView iv_status = subView.findViewById(R.id.iv_my_reservation_status);
                switch (status) {
                    case GlobalConsts.STATUS_NOT_AUDITED:
                        iv_status.setImageResource(R.drawable.not_audited);
                        break;
                    case GlobalConsts.STATUS_PASSED:
                        iv_status.setImageResource(R.drawable.pass);
                        break;
                    case GlobalConsts.STATUS_FAILED:
                        iv_status.setImageResource(R.drawable.not_pass);
                        break;
                }
                //设置教室名，包括教学楼和教室
                Classroom classroom = reservation.getClassroom();
                Building building = classroom.getBuilding();
                TextView tv_classroom = subView.findViewById(R.id.tv_my_reservation_classroom);
                tv_classroom.setText(classroom.getName());
                TextView tv_building = subView.findViewById(R.id.tv_my_reservation_building);
                tv_building.setText(building.getName());
                //设置预约时间段
                Date startTime = reservation.getStart_time();
                Date endTime = reservation.getEnd_time();
                SimpleDateFormat sdf = new SimpleDateFormat("d号HH:mm", Locale.CHINA);
                String timeStr = sdf.format(startTime) + " - " + sdf.format(endTime);
                TextView tv_time = subView.findViewById(R.id.tv_my_reservation_time);
                tv_time.setText(timeStr);
            }
        }
    }

    /**
     * 清洗数据，将reservationList的数据按照月份进行划分
     */
    private void cleanData() {
        if (reservationList == null) {
            Log.d(TAG, "cleanData: reservationList为空！");
            return;
        }
        reservationsMap = new LinkedHashMap<>();
        for (Reservation reservation : reservationList) {
            Date date = getYearMonth(reservation.getStart_time());
            if (!reservationsMap.containsKey(date)) {
                List<Reservation> reservations = new ArrayList<>();
                reservations.add(reservation);
                reservationsMap.put(date, reservations);
            } else {
                reservationsMap.get(date).add(reservation);
            }
        }
        //TODO：记录下，此用法需Android api最低24
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            reservationsMap = reservationList.stream().collect(
//                    Collectors.groupingBy(
//                            this::getYearMonthForJava8,
//                            LinkedHashMap::new,
//                            Collectors.toList()
//                    )
//            );
//        } else {}


    }


    /**
     * 将reservation中的预约时间转换成年和月份
     * 用于java8及以上、Android API 24及以上
     *
     * @param reservation 预约实体
     * @return Date 仅包含年和月部分的时间
     */
    private Date getYearMonthForJava8(Reservation reservation) {
        Date time = reservation.getStart_time();

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        //除年和月外其他时间统一
        calendar.set(Calendar.DATE, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 1);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    /**
     * 用于java8以下、Android API 24以下
     *
     * @param time
     * @return
     */
    private Date getYearMonth(Date time) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        //除年和月外其他时间统一
        calendar.set(Calendar.DATE, 1);
        //小时置零是第二天的零点，所以不能置零，HOUR_OF_DAY是24小时制
        calendar.set(Calendar.HOUR_OF_DAY, 1);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    /**
     * 测试用，创建假数据
     */
    private void createFakeData() {
        ExpandingItem item = reservationExpandingList.createNewItem(R.layout.layout_my_reservation_date);
        item.setIndicatorColor(R.color.may);
        item.setIndicatorIconRes(R.drawable.may);
        //预约的日期（精确到哪个月）
        TextView reservationDate = item.findViewById(R.id.tv_my_reservation_date);
        reservationDate.setText("2019年5月");

        item.createSubItems(2);
        for (int i = 0; i < item.getSubItemsCount(); i++) {
            View subView = item.getSubItemView(i);
            ImageView iv_status = subView.findViewById(R.id.iv_my_reservation_status);
            iv_status.setImageResource(R.drawable.pass);
            TextView tv_classroom = subView.findViewById(R.id.tv_my_reservation_classroom);
            tv_classroom.setText("逸夫楼A101");
            TextView tv_time = subView.findViewById(R.id.tv_my_reservation_time);
            tv_time.setText("26日15:15——26日16:18");
        }
    }

}
